//
//  YQLOAuthViewModel.swift
//  YQL_WeiBo
//
//  Created by apple on 2016/11/16.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
import SVProgressHUD

class YQLOAuthViewModel: NSObject {
    
    //存储网络请求返回的用户信息数据
    var userAccount: YQLUserInfoModel?
    
    //可以使用单例,App只有一个用户登录,当用户注销的时候就会删除用户所有的信息
    static let shared:YQLOAuthViewModel = YQLOAuthViewModel()
    
    //判断用户是否登录的属性-->计算型属性
    var DidLogIn: Bool{
        if self.userAccount?.access_token != nil && isExpires == false {
            return true//已经登录过了
        }
        return false//没有登录
    }
    
    //判断用户的令牌是否过期(Expires过期)
    var isExpires: Bool{
        if userAccount?.expires_date?.compare(Date()) == ComparisonResult.orderedDescending{
            return false
            //没过期
        }
        return true//过期
    }
    
    //用户的头像的url
    var userIconUrl: URL?{
        
        return URL(string: userAccount?.avatar_large ?? "")
        
    }
    
    
    //程序启动的时候给存储用户信息的userAccount赋值,用来判断用户是否登录
    override init() {
        super.init()
        //程序启动调用判断用户是否登录的方法的时候会调用单例对象,必然要初始化对象,会走init方法,这个时候给userAccount赋值
//        print(loadUserInfoModel())
        userAccount = loadUserInfoModel()
//        print(userAccount)
        
    }
    
    
    //获取code后发起网络请求获取AccessToken//https://api.weibo.com/oauth2/access_token
    func getAccesssToken(code: String, finish: @escaping (Bool) -> ()) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id" : "236082640","client_secret" : "b328054250c1a80045713e7cd012db57","grant_type" : "authorization_code","code" : code,"redirect_uri" : "http://www.baidu.com"]
        
        DDNetworkTool.sharedManager.request(Method: .POST, urlString: urlString, parameters: parameters) { (responsObject, error) in
            
            if error != nil{
                finish(false)
                print(error as Any)
                SVProgressHUD.showError(withStatus: "加载Token错误")
                return
            }
            //请求成功,接下来请求用户信息数据
            print("responseObject = ",responsObject as Any)
            
            self.loadUserInfo(dict: responsObject as! [String : Any], complete: finish)
            
        }
        
    }
    
    func loadUserInfo(dict: [String : Any], complete: @escaping (Bool) -> ()) {
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let token = dict["access_token"]
        let uid = dict["uid"]
        let parameters = ["access_token" : token,"uid" : uid];
        DDNetworkTool.sharedManager.request(Method: .GET, urlString: urlString, parameters: parameters) { (responsObject, error) in
            if error != nil {
                print(error as Any)
                SVProgressHUD.showError(withStatus: "加载用户信息失败")
                complete(false)
                return
            }
            //请求成功
            print(responsObject as Any)
            
            var dictUserInfo: [String : Any] = responsObject as! [String : Any]
            for (key,value) in dict{
                
                dictUserInfo[key] = value
            }
            
            //字典转模型
            let userInfoModel = YQLUserInfoModel(dict: dictUserInfo)
            //属性赋值
            self.userAccount = userInfoModel
            //归档
            self.saveUserInfoModel(userInfo: userInfoModel)
            print("^\(self.userAccount?.access_token)")
            complete(true)
        }
    }
    
    
    //归档方法
    func saveUserInfoModel(userInfo: YQLUserInfoModel) {
        
        //路径
        let filePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userInfo.plist")
        
        NSKeyedArchiver.archiveRootObject(userInfo, toFile: filePath)
    }
    
    //解档方法
    func loadUserInfoModel() -> YQLUserInfoModel? {
        
        let filePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userInfo.plist")
        
        let model = NSKeyedUnarchiver.unarchiveObject(withFile: filePath)
        if let userInfoModel = model as? YQLUserInfoModel {
            return userInfoModel
        }
        return nil
    }
    

    

}
